# write by hasaki
# first edit on 2019/04/19
# last change on 2019/05/27
# 合并下载处理交易所的数据和上传到git的功能
import sys
import os
import time
import json
from datetime import datetime
sys.path.append(os.getcwd())

from hashakisea.ui.plotter.matplot import Matplot
from hashakisea.api.digital.gateio import GateIO
from hashakisea.engine.log.logSystem import Ding
from hashakisea.engine.log.logSystem import SaveOnGit

def gateGatewayTest():
    '''测试gateio网关'''
    from hashakisea.api.digital.gateGateway import GateGateway
    print('网关的进程：',os.getpid())
    a=GateGateway()
    a.start()
    a.run()

def tradeTest():
    '''检测交易引擎'''
    from hashakisea.engine.trade.tradeEngine import MainEngine
    from hashakisea.strategy.depthMsg import DepthMsg
    from hashakisea.strategy.tickMsg import TickMsg
    from hashakisea.strategy.haStrategy_1min_test import HaBarTest
    from hashakisea.strategy.updateBarStrategy import UpdateBar
    print('引擎的进程：',os.getpid())
    a=MainEngine()
    a.engingSetting('127.0.0.1',6666)
    a.accountSimulate(3000,100)              # 模拟交易的时候使用的账户资产设置
    a.start()
    s=DepthMsg()
    t=TickMsg()
    b=HaBarTest()
    u=UpdateBar()
    strategy=[{'depth strategy':['depth',s]},{'tick strategy':['tick',t]},{'update tick':['tick',u]},{'update bar':['bar',u]},
    {'tick 1min':['tick',b]},{'bar strategy':['bar',b]}]
    a.strategyIn(strategy)
    a.runSmallStrategy()

def checkTheFile(file_path,global_time):
    '''上传前检查文件'''
    print('文件的进程:',os.getpid())
    new_check=float(os.path.getmtime(file_path))
    if new_check>global_time[0]:
        print('本地文件已更新,准备上传新文件到git',new_check,'hasaki',global_time[0])
        global_time[0]=new_check
        return 1
    else:
        return 0

def upload(file_path,git):
    '''上传到git '''
    #git=SaveOnGit()
    git.file_path=file_path
    git.saveAsGit()
    print('已上传新文件到git 上')

def getKline(a):
    '''获取K线数据'''
    #a=GateIO()
    target_symbol_list=['eos_usdt']
    oglc=[]
    time1=[]
    volume=[]
    for i in target_symbol_list:
        data_return_from_exchange=a.kLine(i,sec=60,hour=24)
        K_line_data=data_return_from_exchange['data']
        for j in K_line_data:
            volume.append(float(j[1]))
            time1.append(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(int(j[0])/1000)))
            oglc.append((float(j[0])/1000,float(j[2]),float(j[3]),float(j[4]),float(j[5])))

    return time1,oglc,volume

def plot(time_,oglc,volume_):
    '''生成行情图 展示k线,time=[],OGLC=[[1,2,3,4],[1,2,3,4],...],更改成matplot打印之后，时间数据也在开高低收里面'''
    e=Matplot()
    e.savePath='C:/Users/cchyp/Desktop/hasaki/quote/last_day/'
    e.time=time_
    e.volume(volume_)
    e.kline(oglc)
    del e

def Kmsg(time_,oglc,volume_):
    '''根据K线数据提炼出，现价和过往最高价和最低价以及成交量信息，json'''
    ding=Ding()
    ding.setting('https://oapi.dingtalk.com/robot/send?access_token=1723b5ff0e5b5b5c522d520aaf79e747f990b598172e241c6f0ef3c693a6b14f')
    last_time=time_[-1]
    last_price=round(oglc[-1][-1]*6.8,4)
    ding.send('时间：{}  最近一小时EOS收盘价:{}'.format(last_time,last_price))

def upload_all(file_path,local_git,global_time,a,g):
    '''上传服务的总和'''
    while 1:
        time_,oglc,volume_=getKline(a)
        plot(time_,oglc,volume_)
        print('生成了新的行情数据')
        #Kmsg(time_,oglc,volume_)
        time.sleep(300)
        is_new= checkTheFile(file_path,global_time)
        if is_new==1:
            #upload(local_git,g)
            pass
        else:
            continue

if __name__=='__main__':
    from multiprocessing import Process

    file_path='C:/Users/cchyp/Desktop/hasaki/quote/last_day/quote.jpg'
    local_git='C:/Users/cchyp/Desktop/hasaki'
    global_time= [float(os.path.getmtime(file_path))]

    get_data_process=Process(target=gateGatewayTest)
    run_trade=Process(target=tradeTest)
    get_data_process.start()
    time.sleep(0.5)
    run_trade.start()
    
    a=GateIO()
    #e=Matplot()
    git=SaveOnGit()
    upload_all(file_path,local_git,global_time,a,git)
